package com.yin.configuration;

import javax.sql.DataSource;

import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

/**
*@author LSY
*Time: 2018年12月28日下午3:35:43
*
*
*/
@Configuration
@EnableScheduling
public class QuartzConfiguration {


	public static class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory
	implements ApplicationContextAware{

		private transient AutowireCapableBeanFactory beanFactory;
		@Override
		public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
			beanFactory = applicationContext.getAutowireCapableBeanFactory();
		}
		
		@Override
		protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
			final Object obj = super.createJobInstance(bundle);
			beanFactory.autowireBean(obj);
			return obj;
		}
	}
	
	@Bean
	public JobFactory jobFactory(ApplicationContext applicationContext) {
		AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
		jobFactory.setApplicationContext(applicationContext);
		return jobFactory;
	}
	
	@Bean
	public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory, DataSource dataSource) {
		SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
		schedulerFactoryBean.setJobFactory(jobFactory);
		schedulerFactoryBean.setOverwriteExistingJobs(true);
		schedulerFactoryBean.setStartupDelay(2);
		schedulerFactoryBean.setAutoStartup(true);
		schedulerFactoryBean.setDataSource(dataSource);
		schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext");
		schedulerFactoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
		return schedulerFactoryBean;
	}
	
}
